package graph.group.zhangtao.guider.getter;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;

import graph.group.zhangtao.guider.utils.CHZipUtils;
import graph.group.zhangtao.guider.utils.GetLocalFiles;
import graph.group.zhangtao.guider.utils.MySettingsAndTools;

/**
 * Created by tao on 18-3-19.
 */

public class DownloadAndUnzip extends AsyncTask {
    private Context context;
    private String name;

    public DownloadAndUnzip(Context context, String name) {
        this.name = name;
        this.context = context;
    }

    @Override
    protected Object doInBackground(Object[] objects) {
        try {
            String encod = URLEncoder.encode(name, "UTF-8");
            Log.w("tao", "start");
            URL url = new URL(MySettingsAndTools.getSourcePath()+encod+".zip");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                Log.w("tao", name);
                File file = new File(GetLocalFiles.getFullDirPath() + name + ".zip");
                if (file.exists()||new File(GetLocalFiles.getFullDirPath() + name).exists()) {
//                    Toast.makeText(context,"文件已存在！",Toast.LENGTH_SHORT).show();
                    return null;
                } else {
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                            new FileOutputStream(file)
                    );
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                    try {
                        byte[] bytes = new byte[1024 * 512];
                        int length = 0;
                        while ((length = bufferedInputStream.read(bytes, 0, bytes.length)) > 0) {
                            bufferedOutputStream.write(bytes, 0, length);
                        }
                        return file;
                    } finally {
                        bufferedOutputStream.flush();
                        bufferedInputStream.close();
                        bufferedInputStream.close();
                    }


                }
            }else {
                return new Integer(3);
            }
        } catch (ProtocolException e) {
            e.printStackTrace();
            return new Integer(2);
        } catch (IOException e) {
            e.printStackTrace();
            return new Integer(1);
        }
    }

    @Override
    protected void onPostExecute(Object o) {
        if (o != null) {
            if(o instanceof Integer){
                Integer code = (Integer)o;
                if(code==1)
                    Toast.makeText(context, "文件读写失败！", Toast.LENGTH_SHORT).show();
                else if(code==2)
                    Toast.makeText(context, "网络协议失败！", Toast.LENGTH_SHORT).show();
                else if(code==3)
                    Toast.makeText(context, "联网错误，请检查网络！", Toast.LENGTH_SHORT).show();

                return;
            }
            try {
                File file = new File(GetLocalFiles.getFullDirPath() + name);
                if(file.exists()){
                    file.delete();
                }
                file.mkdirs();
                CHZipUtils.unZip(((File) o).getAbsolutePath(),file.getAbsolutePath());
                GetLocalFiles.initLocalViewKeys();
                Toast.makeText(context, "下载完成！", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(context, "文件损坏！", Toast.LENGTH_SHORT).show();
                ((File) o).delete();
                new File(name).delete();
            }
        } else {
            Toast.makeText(context, "文件已存在！", Toast.LENGTH_SHORT).show();
        }
    }

//    public static void setImageView(ImageView imageView, String path, String id, String extendPath, boolean fromfile) {
//        if (fromfile) {
//            path = path + id + "/" + extendPath;
//        } else {
//            try {
//                String tempId = URLEncoder.encode(id, "UTF-8");
//                path = path + tempId + "/" + extendPath;
//                new ImageGetterFactory(imageView, path).execute();
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//        }
//    }

}
